package com.zf.nio.channel;

import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @author Zhou Feng
 */
public class FileChannelCopyDemo01 {

    /**
     * FileChannel 的 transferFrom()方法可以将数据从源通道传输到 当前channel 中
     */
    @Test
    public void testTransferFrom() throws IOException {
        FileChannel srcChannel = FileChannel.open(Paths.get("d:\\a.txt"), StandardOpenOption.READ, StandardOpenOption.WRITE);
        FileChannel dstChannel = FileChannel.open(Paths.get("d:\\b.txt"), StandardOpenOption.READ, StandardOpenOption.WRITE);

        try (srcChannel;dstChannel){
            dstChannel.transferFrom(srcChannel, 0L, srcChannel.size());
        }
    }
    /**
     * FileChannel 的 transferFrom()方法可以将数据从当前通道传输到 其他 channel 中
     */
    @Test
    public void testTransferTo() throws IOException {
        FileChannel toChannel = FileChannel.open(Paths.get("d:\\a.txt"), StandardOpenOption.READ, StandardOpenOption.WRITE);
        FileChannel fromChannel = FileChannel.open(Paths.get("d:\\b.txt"), StandardOpenOption.READ, StandardOpenOption.WRITE);

        try (toChannel;fromChannel){
            // 从from 到 to
            fromChannel.transferTo(0L, fromChannel.size(), toChannel);
        }
    }

    /**
     * FileChannel.truncate()方法截取一个文件。截取文件时，原始文件中指定长度后面的部分将被删除,
     */
    @Test
    public void testTruncate() throws IOException {
        FileChannel fileChannel = FileChannel.open(Paths.get("d:\\a.txt"), StandardOpenOption.READ, StandardOpenOption.WRITE);

        try (fileChannel){
            // 返回自身
            FileChannel nc = fileChannel.truncate(2);
            System.out.println(nc==fileChannel); // true

        }
    }

    /**
     *
     */
}
